package com.yn.module.material.config.init;

import com.yn.module.material.pojo.JointGroupPart;
import com.yn.module.material.pojo.JointPartSpec;
import com.yn.module.material.service.JointGroupPartService;
import com.yn.module.material.service.JointPartSpecService;
import com.yn.module.material.utils.constant.DataCache;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @description: 依赖数据初始化
 * @author: 叶甯
 * @create: 2022/9/19 11:22
 * @since: 1.0.0
 * @copyright (C), 2022, https://gitee.com/johnny .All rights reserved.
 */
@Component
public class DataInit implements ApplicationRunner {

    @Resource
    private JointGroupPartService jointGroupPartService;
    @Resource
    private JointPartSpecService jointPartSpecService;

    @Override
    public void run(ApplicationArguments args) throws Exception {

        cacheGoodsId2PartNo();
        cacheJointGroupPart();
    }

    // 缓存JointGroupPart表内容
    private void cacheJointGroupPart() {
        List<JointGroupPart> dataList = jointGroupPartService.list();
        Optional.ofNullable(dataList).orElse(Arrays.asList()).stream().forEach(obj -> {
            // 缓存部件和组套的对应关系
            Set<String> set = DataCache.CachePartNo2Group.get(obj.getPartNo());
            if (set == null) {
                set = new HashSet<>();
                DataCache.CachePartNo2Group.put(obj.getPartNo(), set);
            }
            set.add(obj.getGroupNo());
            // 缓存组套和部件的关系
            List<JointGroupPart> tmpList = DataCache.Cache_Std_Group2Part.get(obj.getGroupNo());
            if (tmpList == null) {
                tmpList = new ArrayList<>();
                DataCache.Cache_Std_Group2Part.put(obj.getGroupNo(), tmpList);
            }
            String chkStr = String.join(",",tmpList.stream().map(JointGroupPart::getPartNo).collect(Collectors.toList()));
            if(!chkStr.contains(obj.getPartNo())) tmpList.add(obj);
        });
    }

    // 缓存国家医保编码与goodsId的对应关系
    private void cacheGoodsId2PartNo() {
        List<JointPartSpec> dataList = jointPartSpecService.list();
        for (JointPartSpec obj : dataList) {
            if (!ObjectUtils.isEmpty(obj.getGoodsId()))
                DataCache.CacheGoodsId2PartNo.put(obj.getGoodsId(), obj.getPartNo());
            if (!ObjectUtils.isEmpty(obj.getMedicareCode()))
                DataCache.CacheGoodsId2PartNo.put(obj.getMedicareCode(), obj.getPartNo());
        }
    }

}
